import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:lmmi/view/time_capsule_sent/page.dart';
import 'package:lmmi/common/index.dart';

void main() {
  group('TimeCapsuleSentPage Tests', () {
    testWidgets('should display loading indicator when loading', (
      WidgetTester tester,
    ) async {
      await tester.pumpWidget(
        ProviderScope(
          overrides: [
            timeCapsuleProvider.overrideWith(
              (ref) =>
                  TimeCapsuleNotifier()
                    ..state = const TimeCapsuleState(isLoading: true),
            ),
          ],
          child: ScreenUtilInit(
            designSize: const Size(375, 812),
            child: MaterialApp(home: TimeCapsuleSentPage()),
          ),
        ),
      );

      expect(find.byType(CircularProgressIndicator), findsOneWidget);
    });

    testWidgets('should display empty state when no time capsules', (
      WidgetTester tester,
    ) async {
      await tester.pumpWidget(
        ProviderScope(
          overrides: [
            timeCapsuleProvider.overrideWith(
              (ref) =>
                  TimeCapsuleNotifier()
                    ..state = const TimeCapsuleState(timeCapsules: []),
            ),
          ],
          child: ScreenUtilInit(
            designSize: const Size(375, 812),
            child: MaterialApp(home: TimeCapsuleSentPage()),
          ),
        ),
      );

      expect(find.text('You Haven\'t Sent Any Letters Yet'), findsOneWidget);
    });

    testWidgets('should display error state when error occurs', (
      WidgetTester tester,
    ) async {
      await tester.pumpWidget(
        ProviderScope(
          overrides: [
            timeCapsuleProvider.overrideWith(
              (ref) =>
                  TimeCapsuleNotifier()
                    ..state = const TimeCapsuleState(error: 'Test error'),
            ),
          ],
          child: ScreenUtilInit(
            designSize: const Size(375, 812),
            child: MaterialApp(home: TimeCapsuleSentPage()),
          ),
        ),
      );

      expect(find.text('Error loading time capsules'), findsOneWidget);
      expect(find.text('Test error'), findsOneWidget);
    });

    testWidgets('should display grid view when time capsules exist', (
      WidgetTester tester,
    ) async {
      final testTimeCapsules = [
        TimeCapsule(
          id: 'test1',
          content: 'Test content 1',
          userId: 'user1',
          createDate: '2024-07-25T10:00:00.000Z',
          openDate: '2025-07-25T10:00:00.000Z',
          description: 'Test description',
          isOpen: false,
          email: 'test@example.com',
          backupEmail: 'backup@example.com',
        ),
        TimeCapsule(
          id: 'test2',
          content: 'Test content 2',
          userId: 'user1',
          createDate: '2024-06-15T14:30:00.000Z',
          openDate: '2025-06-15T14:30:00.000Z',
          description: 'Test description 2',
          isOpen: false,
          email: 'test2@example.com',
          backupEmail: 'backup2@example.com',
        ),
      ];

      await tester.pumpWidget(
        ProviderScope(
          overrides: [
            timeCapsuleProvider.overrideWith(
              (ref) =>
                  TimeCapsuleNotifier()
                    ..state = TimeCapsuleState(timeCapsules: testTimeCapsules),
            ),
          ],
          child: ScreenUtilInit(
            designSize: const Size(375, 812),
            child: MaterialApp(home: TimeCapsuleSentPage()),
          ),
        ),
      );

      expect(find.byType(GridView), findsOneWidget);
      expect(find.text('July 25, 2024'), findsOneWidget);
      expect(find.text('June 15, 2024'), findsOneWidget);
    });

    testWidgets('should clear time capsules when user logs out', (
      WidgetTester tester,
    ) async {
      final testTimeCapsules = [
        TimeCapsule(
          id: 'test1',
          content: 'Test content 1',
          userId: 'user1',
          createDate: '2024-07-25T10:00:00.000Z',
          openDate: '2025-07-25T10:00:00.000Z',
          description: 'Test description',
          isOpen: false,
          email: 'test@example.com',
          backupEmail: 'backup@example.com',
        ),
      ];

      // 创建一个模拟的用户状态管理器
      final userNotifier = UserNotifier();
      final timeCapsuleNotifier = TimeCapsuleNotifier();

      // 设置初始状态：有用户和时间胶囊
      userNotifier.state = UserState(
        currentUser: UserEntity(
          id: 'user1',
          username: 'testuser',
          password: 'password',
          avatar: 'test_avatar.png',
          share: [],
          isVip: false,
          like: [],
        ),
        isLoggedIn: true,
      );
      timeCapsuleNotifier.state = TimeCapsuleState(
        timeCapsules: testTimeCapsules,
      );

      await tester.pumpWidget(
        ProviderScope(
          overrides: [
            userProvider.overrideWith((ref) => userNotifier),
            timeCapsuleProvider.overrideWith((ref) => timeCapsuleNotifier),
          ],
          child: ScreenUtilInit(
            designSize: const Size(375, 812),
            child: MaterialApp(home: TimeCapsuleSentPage()),
          ),
        ),
      );

      // 验证初始状态有时间胶囊
      expect(find.byType(GridView), findsOneWidget);
      expect(find.text('July 25, 2024'), findsOneWidget);

      // 模拟用户退出登录
      userNotifier.state = const UserState();
      await tester.pump();

      // 验证时间胶囊列表被清空，显示空状态
      expect(find.text('You Haven\'t Sent Any Letters Yet'), findsOneWidget);
      expect(find.byType(GridView), findsNothing);
    });
  });
}
